<template>
	<view class="container">
		<!-- 按钮组 -->
		<view class="button-group">
			<button @tap="openBluetoothAdapter" :disabled="scanning" class="btn-primary">开始扫描</button>
			<button @tap="stopBluetoothDevicesDiscovery" :disabled="!scanning" class="btn-secondary">停止扫描</button>
			<button @tap="closeBluetoothAdapter" class="btn-tertiary">结束流程</button>
		</view>

		<!-- 设备扫描结果 -->
		<view class="section-title">设备发现</view>
		<view class="devices-summary">找到 {{devices.length}} 台设备</view>
		<scroll-view class="device-list" scroll-y>
			<view v-for="(item, index) in devices" :key="index" :data-device-id="item.deviceId"
				:data-name="item.name || item.localName" @tap="createBLEConnection" class="device-item">
				<view class="device-name">{{item.name || item.localName || '未知设备'}}</view>
				<view class="device-info">信号: {{item.RSSI}}dBm ({{calculateSignalPercentage(item.RSSI)}}%)</view>
				<view class="device-info">ID: {{truncateUuid(item.deviceId)}}</view>
				<view class="device-info">服务: {{calculateServiceCount(item.advertisServiceUUIDs)}}</view>
			</view>
			<view v-if="devices.length === 0 && !scanning" class="empty-state">
				未发现目标血压计，请点击“开始扫描”
			</view>
		</scroll-view>

		<!-- 连接状态与测量结果 -->
		<view class="result-panel" v-if="connected">
			<view class="connection-status">
				<text class="device-connected">已连接: {{name}}</text>
				<button size="mini" @tap="closeBLEConnection" class="disconnect-btn">断开</button>
			</view>

			<!-- 血压测量结果显示 -->
			<view class="measurement-result" v-if="bloodPressureData">
				<view class="result-title">测量完成</view>
				<view class="vital-sign systolic">
					<text class="label">收缩压</text>
					<text class="value">{{bloodPressureData.systolic}}</text>
					<text class="unit">mmHg</text>
				</view>
				<view class="vital-sign diastolic">
					<text class="label">舒张压</text>
					<text class="value">{{bloodPressureData.diastolic}}</text>
					<text class="unit">mmHg</text>
				</view>
				<view class="vital-sign pulse">
					<text class="label">脉搏</text>
					<text class="value">{{bloodPressureData.pulse}}</text>
					<text class="unit">次/分</text>
				</view>
				<view class="measurement-time">
					测量时间: {{bloodPressureData.timestamp}}
				</view>
			</view>

			<view v-else class="measurement-prompt">
				正在等待血压计测量数据...
			</view>
		</view>
	</view>
</template>

<script>
	// 保留 inArray 函数用于列表更新
	function inArray(arr, key, val) {
		if (!arr || !Array.isArray(arr)) return -1;
		for (let i = 0; i < arr.length; i++) {
			if (arr[i][key] === val) {
				return i;
			}
		}
		return -1;
	}

	// 优化后的自定义血压数据解析函数（移除时间解析）
	function parseCustomBloodPressureData(data) {
		console.log("解析血压数据, 长度:", data.length);
		console.log("原始数据:", Array.from(data));

		if (!data || data.length < 15) {
			console.log('数据长度不足:', data ? data.length : 'null');
			return null;
		}

		// 直接提取血压值
		const systolic = data[1] & 0xFF; // 位置1
		const diastolic = data[3] & 0xFF; // 位置3
		const pulse = data[14] & 0xFF; // 位置14

		// 基本校验 (可选: 检查值是否在合理范围内)
		if (systolic < 50 || systolic > 250 ||
			diastolic < 30 || diastolic > 150 ||
			pulse < 30 || pulse > 200) {
			console.log('血压值超出合理范围，可能解析错误');
			return null;
		}

		console.log('解析成功 - 收缩压:', systolic, '舒张压:', diastolic, '脉搏:', pulse);
		return {
			systolic,
			diastolic,
			pulse,
			rawData: Array.from(data)
		};
	}

	// 格式化时间显示 (使用系统时间)
	function formatTimestamp(date) {
		if (!date || !(date instanceof Date)) return '未知时间';
		const pad = (n) => n.toString().padStart(2, '0');
		return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`;
	}

	export default {
		data() {
			return {
				devices: [],
				connected: false,
				name: '',
				deviceId: '',
				_discoveryStarted: false,
				scanning: false,
				bloodPressureData: null
			}
		},
		methods: {
			calculateSignalPercentage(rssi) {
				return Math.max(0, (rssi || 0) + 100);
			},
			calculateServiceCount(services) {
				return services ? services.length : 0;
			},
			truncateUuid(uuid) {
				// 简化长UUID显示
				if (!uuid) return '';
				return uuid.length > 8 ? uuid.slice(-8) : uuid;
			},
			openBluetoothAdapter() {
				if (this.scanning) return;
				uni.showLoading({
					title: '初始化蓝牙...'
				});
				uni.openBluetoothAdapter({
					success: (res) => {
						console.log('蓝牙适配器打开成功');
						uni.hideLoading();
						this.startBluetoothDevicesDiscovery();
					},
					fail: (res) => {
						console.log('蓝牙适配器打开失败', res);
						uni.hideLoading();
						uni.showModal({
							title: '蓝牙错误',
							content: '请检查手机蓝牙是否开启',
							showCancel: false
						});
					}
				});
			},
			startBluetoothDevicesDiscovery() {
				if (this._discoveryStarted || this.scanning) return;
				this._discoveryStarted = true;
				this.scanning = true;
				uni.showLoading({
					title: '扫描中...'
				});
				uni.startBluetoothDevicesDiscovery({
					allowDuplicatesKey: true,
					success: (res) => {
						console.log('开始扫描成功');
						uni.hideLoading();
						this.onBluetoothDeviceFound();
					},
					fail: (res) => {
						console.log('开始扫描失败', res);
						uni.hideLoading();
						this._discoveryStarted = false;
						this.scanning = false;
						uni.showToast({
							title: '扫描失败',
							icon: 'none'
						});
					}
				});
			},
			stopBluetoothDevicesDiscovery() {
				uni.stopBluetoothDevicesDiscovery();
				this._discoveryStarted = false;
				this.scanning = false;
				uni.showToast({
					title: '已停止',
					icon: 'success'
				});
			},
			onBluetoothDeviceFound() {
				uni.onBluetoothDeviceFound((res) => {
					if (res.devices && res.devices.length > 0) {
						res.devices.forEach(device => {
							const deviceName = device.name || device.localName;
							if (!deviceName || deviceName !== "BP06D2A2406050768") return;
							const idx = inArray(this.devices, 'deviceId', device.deviceId);
							if (idx === -1) {
								this.devices.push(device);
							} else {
								this.$set(this.devices, idx, device);
							}
						});
					}
				});
			},
			createBLEConnection(e) {
				const deviceId = e.currentTarget.dataset.deviceId;
				const name = e.currentTarget.dataset.name;
				uni.showLoading({
					title: '连接中...'
				});
				uni.createBLEConnection({
					deviceId,
					success: (res) => {
						uni.hideLoading();
						this.connected = true;
						this.name = name;
						this.deviceId = deviceId;
						this.getBLEDeviceServices(deviceId);
						uni.showToast({
							title: '连接成功',
							icon: 'success'
						});
					},
					fail: (res) => {
						uni.hideLoading();
						console.log('连接失败', res);
						uni.showToast({
							title: '连接失败',
							icon: 'none'
						});
					}
				});
				this.stopBluetoothDevicesDiscovery();
			},
			closeBLEConnection() {
				if (this.deviceId) {
					uni.closeBLEConnection({
						deviceId: this.deviceId
					});
				}
				this.resetConnectionState();
				uni.showToast({
					title: '已断开',
					icon: 'success'
				});
			},
			resetConnectionState() {
				// 重置所有连接相关状态
				this.connected = false;
				this.name = '';
				this.deviceId = '';
				this.bloodPressureData = null;
			},
			getBLEDeviceServices(deviceId) {
				console.log("获取服务...");
				uni.getBLEDeviceServices({
					deviceId,
					success: (res) => {
						console.log('服务:', res.services);
						if (res.services && res.services.length > 0) {
							const primaryService = res.services.find(s => s.isPrimary) || res.services[0];
							if (primaryService) {
								this.getBLEDeviceCharacteristics(deviceId, primaryService.uuid);
							}
						} else {
							uni.showToast({
								title: '无服务',
								icon: 'none'
							});
						}
					},
					fail: (res) => {
						console.log('获取服务失败', res);
						uni.showToast({
							title: '获取服务失败',
							icon: 'none'
						});
					}
				});
			},
			getBLEDeviceCharacteristics(deviceId, serviceId) {
				this.setupBLECharacteristicValueChangeListener();
				uni.getBLEDeviceCharacteristics({
					deviceId,
					serviceId,
					success: (res) => {
						console.log('特征值:', res.characteristics);
						if (res.characteristics && res.characteristics.length > 0) {
							for (let item of res.characteristics) {
								if (item.properties.notify || item.properties.indicate) {
									uni.notifyBLECharacteristicValueChange({
										deviceId,
										serviceId,
										characteristicId: item.uuid,
										state: true,
									}).catch(err => {
										console.error('开启通知失败:', err);
										// uni.showToast({
										// 	title: '通知开启失败',
										// 	icon: 'none'
										// });
									});
								}
							}
							console.log('已开启通知，等待数据...');
						} else {
							uni.showToast({
								title: '无特征值',
								icon: 'none'
							});
						}
					},
					fail: (res) => {
						console.error('获取特征值失败', res);
						uni.showToast({
							title: '获取特征值失败',
							icon: 'none'
						});
					}
				});
			},
			setupBLECharacteristicValueChangeListener() {
				uni.offBLECharacteristicValueChange(); // 清理旧监听
				uni.onBLECharacteristicValueChange((characteristic) => {
					console.log("收到数据:", characteristic.characteristicId);
					if (characteristic.value instanceof ArrayBuffer) {
						try {
							const dataArray = new Uint8Array(characteristic.value);
							console.log("数据:", Array.from(dataArray));

							const bpData = parseCustomBloodPressureData(dataArray);
							if (bpData) {
								// 使用系统当前时间
								bpData.timestamp = formatTimestamp(new Date());
								this.bloodPressureData = bpData;
								uni.showToast({
									title: '测量完成',
									icon: 'success'
								});
								console.log('血压数据:', bpData);
							} else {
								console.log("数据包无效或非血压数据");
							}
						} catch (error) {
							console.error("数据处理错误:", error);
						}
					}
				});
			},
			closeBluetoothAdapter() {
				if (this.connected) {
					this.closeBLEConnection();
				}
				uni.closeBluetoothAdapter({
					success: () => console.log('蓝牙已关闭'),
					fail: (err) => console.error('关闭失败', err)
				});
				this._discoveryStarted = false;
				this.scanning = false;
				this.devices = [];
				this.bloodPressureData = null;
				uni.showToast({
					title: '蓝牙已关闭',
					icon: 'success'
				});
			}
		},
		onUnload() {
			this.closeBluetoothAdapter();
			uni.offBLECharacteristicValueChange();
		}
	}
</script>

<style>
	.container {
		padding: 30rpx;
		color: #333;
		min-height: 100vh;
		background-color: #f5f7fa;
		font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', sans-serif;
	}

	/* 按钮组 */
	.button-group {
		display: flex;
		justify-content: space-between;
		margin-bottom: 30rpx;
		flex-wrap: wrap;
		gap: 20rpx;
	}

	.button-group button {
		flex: 1;
		min-width: 200rpx;
		margin: 0;
	}

	.btn-primary {
		background-color: #007AFF;
		color: white;
	}

	.btn-secondary {
		background-color: #5856D6;
		color: white;
	}

	.btn-tertiary {
		background-color: #FF3B30;
		color: white;
	}

	button:disabled {
		opacity: 0.6;
	}

	/* 标题和摘要 */
	.section-title {
		font-size: 36rpx;
		font-weight: 600;
		color: #1a1a1a;
		margin-bottom: 20rpx;
	}

	.devices-summary {
		font-size: 28rpx;
		color: #666;
		margin-bottom: 20rpx;
	}

	/* 设备列表 */
	.device-list {
		flex: 1;
		background-color: white;
		border-radius: 16rpx;
		border: 1px solid #e0e0e0;
		overflow: hidden;
		margin-bottom: 30rpx;
	}

	.device-item {
		padding: 30rpx;
		border-bottom: 1px solid #f0f0f0;
	}

	.device-item:last-child {
		border-bottom: none;
	}

	.device-name {
		font-size: 32rpx;
		font-weight: 500;
		color: #1a1a1a;
		margin-bottom: 10rpx;
	}

	.device-info {
		font-size: 24rpx;
		color: #888;
	}

	.empty-state {
		text-align: center;
		padding: 60rpx 0;
		color: #999;
		font-style: italic;
	}

	/* 结果面板 */
	.result-panel {
		background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
		padding: 40rpx;
		border-radius: 20rpx;
		color: white;
		box-shadow: 0 10rpx 30rpx rgba(0, 0, 0, 0.15);
	}

	.connection-status {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 30rpx;
	}

	.device-connected {
		font-size: 32rpx;
		font-weight: 500;
	}

	.disconnect-btn {
		background-color: rgba(255, 255, 255, 0.2);
		color: white;
	}

	/* 测量结果 */
	.measurement-result {
		text-align: center;
	}

	.result-title {
		font-size: 36rpx;
		font-weight: bold;
		margin-bottom: 40rpx;
		text-shadow: 0 2rpx 4rpx rgba(0, 0, 0, 0.3);
	}

	.vital-sign {
		display: flex;
		align-items: baseline;
		justify-content: center;
		margin-bottom: 20rpx;
	}

	.label {
		font-size: 28rpx;
		margin-right: 15rpx;
		opacity: 0.9;
	}

	.value {
		font-size: 60rpx;
		font-weight: bold;
		margin: 0 10rpx;
	}

	.unit {
		font-size: 28rpx;
		opacity: 0.8;
	}

	.systolic .value {
		color: #ff6b6b;
	}

	.diastolic .value {
		color: #4ecdc4;
	}

	.pulse .value {
		color: #45b7d1;
	}

	.measurement-time {
		font-size: 26rpx;
		margin-top: 30rpx;
		opacity: 0.8;
	}

	.measurement-prompt {
		text-align: center;
		font-size: 28rpx;
		opacity: 0.8;
		padding: 40rpx 0;
	}
</style>